<?php
require_once 'application/libraries/PieChartLibrary.php';

class ReportesController extends CI_Controller{
    
    public function index() {
        $this->loadDefaultData();
    }
    
    public function loadDefaultData(){
        
        $this->load->model('SpecialtyModel');
        $this->load->model('ApointmentModel');
        
        $specialties = $this->SpecialtyModel->getSpecialties();
        
        $data['filterCondition'] = "";
        $data['specialties'] = $specialties;
        $data['apointmentStates'] = $this->ApointmentModel->getApointmentStates();
        
        $data['pieChartScript'] = $this->getDefaultPieChart();
        
        $data['barChartScript'] = $this->getDefaultBarChart();
        $data['barChartDivWidth'] = 500;
        $data['ratedDoctors'] = $this->countAndSaveDoctors();
        
        $this->load->view('view_ver_reportes', $data);
    }
    
    public function getDefaultPieChart(){
        $chartController = new PieChartLibrary();
        $quantity = $this->ApointmentModel->getAllApointments();
        $apointmentsByType = array("$quantity[1]", "$quantity[2]", "$quantity[3]", "$quantity[4]", "$quantity[5]", 
            "$quantity[6]", "$quantity[7]", "$quantity[8]");
        $defaultPieChart = $chartController->loadPieChart($apointmentsByType);
        return $defaultPieChart;
    }
    
    public function getDefaultBarChart(){
        $chartController = new PieChartLibrary();
        
        
        $apTypes = array("Reservada","Inconclusa","Cancelada","Atendida", "Calificada");
        
        $specialty1 = array("Oncología",1000, 400, 500, 102, 65);
        $specialty2 = array("Pediatría",1170, 460, 600, 82, 12);
        $specialty3 = array("Cardiología",660, 1120, 250, 52, 84);
        $specialty4 = array("Hematologia",610, 120, 250, 79, 32);
        
        $specialtiesArray = array($specialty1,$specialty2,$specialty3,$specialty4);
        
        
        $defaultBarChart = $chartController->loadBarChart($apTypes, $specialtiesArray);
        return $defaultBarChart;
    }
    
    
    public function applyFilter(){
        
        $specialtyId = $this->input->post('specialty');
        $startDate = $this->reformatDate($this->input->post('startDate'));
        $endDate = $this->reformatDate($this->input->post('endDate'));
        
        if($specialtyId == "0" &&  $startDate ==""  && $endDate =="" ){
            // buscar todas las citas
            //echo 'todas las citas ';
            $this->calculateAllApointments();
            
        }else{
            if( $startDate != "" && $endDate != "" ){
                if( $specialtyId != "0" ){
                    // buscar todas las citas agrupadas por especialidad y fecha
                    //echo 'citas por especialidad y fecha ';
                    $this->apointmentsByDateAndSpecialty($specialtyId, $startDate, $endDate);
                }else{
                    // buscar todas las citas por fecha
                    //echo 'citas por fecha ';
                    
                    $this->calculateByDate($startDate, $endDate);
                    
                    
                }
            }else{
                $this->calculateApointmentBySpecialty($specialtyId);
                 // buscar todas las citas por especialidad
                 //echo 'citas por especialidad ';
            }
        }
        
        
        
        //echo 'especialidad: '.$specialty;
        //echo 'fecha inicio: '.$startDate;
        //echo 'fecha fin: '.$endDate;
    }
    
    
    
    
    
    public function calculateAllApointments(){
        $this->load->model('SpecialtyModel');
        $this->load->model('ApointmentModel');
        $data['specialties'] = $this->SpecialtyModel->getSpecialties();
        $data['apointmentStates'] = $this->ApointmentModel->getApointmentStates();
        $data['filterCondition'] = "";
        $quantity = $this->ApointmentModel->getAllApointments();
        $this->getApointmentsByCondition($data, $quantity);
    }
    
    
    
    public function apointmentsByDateAndSpecialty($specialtyId, $startDate, $endDate){
        $this->load->model('SpecialtyModel');
        $this->load->model('ApointmentModel');
        
        $data['specialties'] = $this->SpecialtyModel->getSpecialties();
        $data['apointmentStates'] = $this->ApointmentModel->getApointmentStates();
        //titulo del resultado
        $specialty = $this->SpecialtyModel->getSpecialtyInfoById($specialtyId);
        
        $_startDate = $this->getDateAttributes($startDate);
        $_endDate = $this->getDateAttributes($endDate);
        $filterCondition = " del ".$_startDate['day']." de ".$_startDate['month'].' del '.$_startDate['year'].'  al  '.
                $_endDate['day']." de ".$_endDate['month'].' del '.$_endDate['year'].' por '.$specialty["nombre_especialidad"];
        $data['filterCondition'] = $filterCondition;
        // fin de titulo del resultado
        $quantity = $this->ApointmentModel->getApointmentsByDateAndSpecialty($specialtyId, $startDate, $endDate);
        $this->getApointmentsByCondition($data, $quantity);
    }
    
    
    public function calculateApointmentBySpecialty($specialtyId){
        $this->load->model('SpecialtyModel');
        $this->load->model('ApointmentModel');
        
        //titulo del resultado
        $specialty = $this->SpecialtyModel->getSpecialtyInfoById($specialtyId);
        $filterCondition = " por ".$specialty["nombre_especialidad"];
        $data['filterCondition'] = $filterCondition;
        // fin de titulo del resultado
        
        $data['specialties'] = $this->SpecialtyModel->getSpecialties();
        $data['apointmentStates'] = $this->ApointmentModel->getApointmentStates();
        $quantity = $this->ApointmentModel->getApointmentsBySpecialty($specialtyId);
        
        $this->getApointmentsByCondition($data, $quantity);
    }
    
    
    public function calculateByDate($startDate, $endDate){
        $this->load->model('SpecialtyModel');
        $this->load->model('ApointmentModel');
        
        
        //titulo del resultado
        $_startDate = $this->getDateAttributes($startDate);
        $_endDate = $this->getDateAttributes($endDate);
        $filterCondition = " del ".$_startDate['day']." de ".$_startDate['month'].' del '.$_startDate['year'].'  al  '.
                $_endDate['day']." de ".$_endDate['month'].' del '.$_endDate['year'];
        $data['filterCondition'] = $filterCondition;
        // fin de titulo del resultado
        
        $data['specialties'] = $this->SpecialtyModel->getSpecialties();
        $quantity = $this->ApointmentModel->getApointmentsByDate($startDate, $endDate);
        $this->getApointmentsByCondition($data, $quantity);
    }
    
    
    public function getApointmentsByCondition($data, $quantity){
        $pieController = new PieChartLibrary();
        $apointmentsByType = array("$quantity[1]", "$quantity[2]", "$quantity[3]", "$quantity[4]", "$quantity[5]", 
            "$quantity[6]", "$quantity[7]", "$quantity[8]");
        $data['pieChartScript'] = $pieController->loadPieChart($apointmentsByType);
        $data['barChartScript'] = $this->getDefaultBarChart();
        $data['cantidad'] = 8;
        $this->load->view('view_ver_reportes', $data);
    }
    
    // compability method for dates
    public function reformatDate($date){
        if ($date != "") {
            $year = substr($date, -4);
            $month = substr($date, 3, -5);
            $day = substr($date, 0, -8);
            $date = $year.'-'.$month.'-'.$day;
        }
        
        return $date;
    }
    
    
    public function getDateAttributes($date){
        
        $array = array();
        switch(date("n", strtotime($date))){
            case '1':
                $month = 'Enero';
                break;
            case '2':
                $month = 'Febrero';
                break;
            case '3':
                $month = 'Marzo';
                break;
            case '4':
                $month = 'Abril';
                break;
            case '5':
                $month = 'Mayo';
                break;
            case '6':
                $month = 'Junio';
                break;
            case '7':
                $month = 'Julio';
                break;
            case '8':
                $month = 'Agosto';
                break;
            case '9':
                $month = 'Septiembre';
                break;
            case '10':
                $month = 'Octubre';
                break;
            case '11':
                $month = 'Noviembre';
                break;
            case '12':
                $month = 'Diciembre';
                break;
            default:
                break;
        }
        
        $array['day'] = date("j", strtotime($date));
        $array['month'] = $month;
        $array['year'] = date("Y", strtotime($date));
        return $array;
    }
    
    
    
    
    
    
    
    
    // barChart
    
    
    
    
    
    
    
    public function applyFilterVS(){
        
        $chartController = new PieChartLibrary();
        $this->load->model('SpecialtyModel');
        $this->load->model('ApointmentModel');
        
        $specialties = $this->SpecialtyModel->getSpecialties();
        $apointments = $this->ApointmentModel->getApointmentStates();
        
        $data['filterCondition'] = "";
        $data['specialties'] = $specialties;
        $data['apointmentStates'] = $apointments;
        $data['pieChartScript'] = $this->getDefaultPieChart();
        $data['ratedDoctors'] = $this->countAndSaveDoctors();
            
        $selectedSpecialtiesId = $this->getSelectedSpecialtiesId(count($specialties));
        $selectedApointmentsId = $this->getSelectedApointmentsType(count($apointments));
        
        
            $arrayApointmentStates = $this->getApointmentsNameArray($selectedApointmentsId);
            $arraySpecialtiesAndValues = $this->getSpecialtiesArray($selectedApointmentsId, $selectedSpecialtiesId);
        
            $data['barChartScript'] = $chartController->loadBarChart($arrayApointmentStates, $arraySpecialtiesAndValues);
            $data['barChartDivWidth'] = $this->resizebarChartDiv(count($arraySpecialtiesAndValues));
        
        
        $this->load->view('view_ver_reportes', $data);
        
    }
    
    
    public function getSelectedSpecialtiesId($quantity){
        
        $selectedSpecialtiesId = array();
        for($i=1;$i<=$quantity;$i++){
            if(isset($_POST['spec'.$i])) {
                $specialtyId = $_POST['spec'.$i];
                //echo 'marcado: checkbox '.$i.'  y especialidad:   '.$specialtyId.'<br>';
                $selectedSpecialtiesId[] = $specialtyId;
                
            }
        }
        return $selectedSpecialtiesId;
    }
    
    public function getSelectedApointmentsType($quantity){
        $selectedApointmentsId = array();
        for($i=1;$i<=$quantity;$i++){
            if(isset($_POST['tipo'.$i])) {
                $apointmentId = $_POST['tipo'.$i];
                //echo 'marcado: checkbox '.$i.'  y especialidad:   '.$specialtyId.'<br>';
                $selectedApointmentsId[] = $apointmentId;
            }
        }
        return $selectedApointmentsId;
    }
    
    public function getApointmentsNameArray($apointmentsArray){
        $this->load->model('ApointmentModel');
        $array = array();
        for($i=0;$i<count($apointmentsArray);$i++){
            $array[] = $this->ApointmentModel->getNameByStateId($apointmentsArray[$i]);
        }
        return $array;
    }
    
    
    
    public function getSpecialtiesArray($arrayApointmentStatesId, $arraySpecialtiesId){
        $this->load->model('SpecialtyModel');
        $this->load->model('ApointmentModel');
        $allSpecialties = array();
        
        for($i=0; $i<count($arraySpecialtiesId); $i++){
            
            $specialtyArray = array();
            $specialtyName = $this->SpecialtyModel->getSpecialtyNameById($arraySpecialtiesId[$i]);
            $specialtyArray[] = $specialtyName[0]->nombre_especialidad;
        
            for($j=0; $j<count($arrayApointmentStatesId); $j++){
                $specialtyArray[] = $this->ApointmentModel->getApointmentsQuantityByIdAndSpecialty($arrayApointmentStatesId[$j], $arraySpecialtiesId[$i]);
            }
            $allSpecialties[] = $specialtyArray;
        }
        return $allSpecialties;
    }
    
    
    
    public function resizebarChartDiv($apointmentsQuantity){
        $size = 150*$apointmentsQuantity;
        if ($size<500) {
            $size=500;
        }
        return $size;
    }
    
    // end BarChart
    
    
    public function countAndSaveDoctors(){
        $doctorsArray = array();
        $this->load->model('DoctorModel');
        $doctors = $this->DoctorModel->getQuantityRatedDoctors();
        foreach($doctors as $doctor){
            $pointsArray = $this->getPointsByDoctorId($doctor->ID_DOCTOR);
            $average = $this->getAverage($pointsArray);
            $doctorInfo = $this->DoctorModel->getDoctorArrayById($doctor->ID_DOCTOR);
            $doctorInfo['average'] = $average;
            $doctorsArray[] = $doctorInfo;
        }
        return $doctorsArray;
    }
    
    public function getPointsByDoctorId($doctorId){
        $this->load->model('DoctorModel');
        $ratedDoctors = $this->DoctorModel->getRatedDoctor($doctorId);
        return $ratedDoctors;
    }
    
    public function getAverage($points){
        $average = 0;
        foreach($points as $point){
            $average = $average + (int)$point->calificacion;
        }
        return $average/count($points);
    }
    
    
    
}



?>
